<template>
<div style="height: 100%">
  <el-row type="flex">
    <el-col :span="6" class="bg-white h-full">
      <recipient-select-tab v-model:recipient="recipient"
                            v-model:labels="form.recipient"
                            @check="handleCheckRecipient"
                            ref="recipientSelectTree"/>
    </el-col>
    <el-col :span="18" class="bg-white scrollbar-new" style="color: #323338">
      <div class="flex-space-between" style="height: 70px;">
        <span class="font-size-18 font-bold">
          <span>{{ $t('loc.sendGroup') }}</span>
<!--          <div class="inline">-->
<!--            &lt;!&ndash;                点击帮助的按钮&ndash;&gt;-->
<!--            <a href="https://learninggenie.zendesk.com/hc/en-us/articles/360038888494-How-can-I-send-out-announcements-or-notifications-to-my-staff-or-families-School-Message-" target="_blank">-->
<!--              <el-tooltip effect="dark" :content="$t('loc.help')" placement="top">-->
<!--                <img-->
<!--                  style="position: relative; bottom: 3px; left: 10px; cursor: pointer; filter: opacity(0.75);"-->
<!--                  src="@/assets/img/us/Reminder.png">-->
<!--              </el-tooltip>-->
<!--            </a>-->
<!--          </div>-->
        </span>
        <!-- 发送类型 -->
        <!-- 发送类型 -->
        <send-setting v-model="form.sendType" ref="sendType"/>
      </div>
      <el-form ref="form" :model="form" :rules="rules" class="m-t-xs">
        <!-- 接收人 -->
        <el-form-item prop="recipient" ref="recipientFormItem">
          <recipient-select v-model="form.recipient" ref="recipientSelect"/>
        </el-form-item>
        <!-- 标题 -->
        <el-form-item prop="subject" ref="subjectFormItem">
          <el-input class="school-message-subject__input"
                    v-model="form.subject"
                    :placeholder="$t('loc.subj')"
                    maxlength="150"
                    show-word-limit/>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item prop="content" ref="contentFormItem">
          <el-input
              v-model="form.content"
              placeholder="Please input"
              show-word-limit
              :autosize="{ minRows: 20, maxRows: 20 }"
              type="textarea"
          />
        </el-form-item>
        <!-- 附件 -->
        <el-form-item>
        </el-form-item>
        <el-divider/>
        <!-- 发送按钮 -->
        <div style="text-align: right;margin-bottom: 20px">
          <el-button type="primary" size="medium" @click="handleClickSend" :loading="sending">
            {{ $t('loc.send') }}
          </el-button>
        </div>
      </el-form>
      <!-- 发送结果回显 -->
      <el-dialog v-model:visible="sendResult.show" :close-on-click-modal="false">
        <div slot="title" class="font-size-20">{{ $t('loc.sendRecord') }}</div>
        <ul class="sendRecordsUl">
          <li v-show="sendResult.sendType ==='Recommend' || sendResult.sendType ==='SMS'">
            <span><img src="@/assets/img/message/iphone.png" alt=""/></span>
            <span>
                <span class="m-l-xs">By sms</span>:
                <span class="m-l-xs">{{ sendResult.appTypeMessageCount }}</span>
            </span>
          </li>
          <li class="m-t-sm" v-show="sendResult.sendType==='Recommend' || sendResult.sendType==='EMAIL'">
            <span><img src="@/assets/img/message/email2.png" alt=""/></span>
            <span>
                <span class="m-l-xs">By email</span>:
                <span class="m-l-xs">{{ sendResult.emailTypeMessageCount }}</span>
            </span>
          </li>
        </ul>
        <template slot="footer">
          <el-button @click="handleClickCloseSendResult">
            {{ $t('loc.close') }}
          </el-button>
        </template>
      </el-dialog>
    </el-col>
  </el-row>
  <div v-if="showUndoBox">
    <undo-message
      :tip="undoTip"
      :show-button="showUndoButton"
      @close="showUndoBox = false"
      @undo="undoSend"/>
  </div>

</div>
</template>

<script>
import MessageApi from "@/api/message";
import UndoMessage from "@/views/modules/component/UndoMessage";
import RecipientSelectTab from "@/views/modules/message/MessageCreate/Recipient/RecipientSelectTab";
import RecipientSelect from "@/views/modules/message/MessageCreate/Recipient/RecipientSelect";
import SendSetting from "@/views/modules/message/MessageCreate/SendSetting";

export default {
  name: "MessageCreate",
  components: {
    UndoMessage,
    RecipientSelectTab,
    RecipientSelect,
    SendSetting
  },
  data() {
    return {
      form: {
        sendType: 'EMAIL', // 消息发送类型：EMAIL、SMS 、Recommend、APP
        recipient: {}, // 已选接收人 label : staff、parent
        staffCenterIds: [], // 已选接收人--幼儿园所有老师
        staffGroupIds: [], // 已选接收人--班级所有老师
        staffIds: [], // 已选接收人--老师
        childCenterIds: [], // 已选接收人--幼儿园所有小孩
        childGroupIds: [], // 已选接收人--班级所有小孩
        childIds: [], // 已选接收人--小孩
        subject: null, // 消息标题
        content: '', // 消息内容
        attachments: [], // 消息附件：fileId、fileName
      },
      rules: {
        recipient: [{validator: this.validateRecipient}],
        subject: [{message: this.$t('loc.fieldReq'), required: true, whitespace: true, trigger: 'change'}],
        content: [{message: this.$t('loc.fieldReq'), required: true, transform: value => this.innerText(value)}]
      },
      attachments: [],
      recipient: [], // 已选接收人
      sending: false, // 发送状态
      sendResult: {
        show: true,
        sendType: '',
        appTypeMessageCount: '',
        emailTypeMessageCount: '',
      },
      showUndoBox: false,
      undoTip: this.$t('loc.MessageSent'),
      showUndoButton: false,
      messageId: '',
      history: {},
      undoing: false
    }
  },
  computed: {
    receiveRole() {
      let result = [];
      let {staff = [], parent = []} = this.form.recipient;
      staff.length && result.push("STAFF")
      parent.length && result.push("PARENT")
      return result.join(",");
    }
  },
  watch: {
    recipient(value) {
      Object.assign(this.form, value);
    },
    $route () {
      this.showUndoButton = false
      this.showUndoBox = false
    }
    },
  methods: {
    innerText(html) {
      if (html.includes('<img')) {
        return 'img';
      }
      let htmlDivElement = document.createElement('div');
      htmlDivElement.innerHTML = html || '';
      return htmlDivElement.innerText.trim();
    },
    validateRecipient(rule, value, callback) {
      let {staff = [], parent = []} = value || {};
      if (!staff.length && !parent.length) {
        callback(new Error(this.$t('loc.fieldReq').toString()));
      } else {
        callback();
      }
    },
    async handleClickSend() {
      this.showUndoButton = false
      this.showUndoBox = false
      // 校验
      try {
        await this.$refs.form.validate();
      } catch (e) {
        return;
      }
      this.sending = true;
      // 数据收集
      let {form, receiveRole, attachments} = this;
      let {sendType, subject, content, staffCenterIds, staffIds, childCenterIds, childGroupIds, childIds} = form;
      this.history.form = {sendType, subject, content, staffCenterIds, staffIds, childCenterIds, childGroupIds, childIds}
      this.history.form.recipient = form.recipient
      this.history.receiveRole = receiveRole
      this.history.attachments = attachments
      this.history.recipient = this.recipient
      this.history.checkes = this.$refs.recipientSelectTree.getChecks()
      let sendAtLocal = this.$moment().format('YYYY-MM-DD HH:mm:ss.SSS');
      attachments = attachments.map(({id, name}) => ({fileId: id, fileName: name}));

      console.log('this.history', {
        receiveRole, sendType, sendAtLocal, subject, content, attachments,
        staffCenterIds, staffIds, childCenterIds, childGroupIds, childIds
      })
      // 发送消息
      MessageApi.sendMessage({
        receiveRole, sendType, sendAtLocal, subject, content, attachments,
        staffCenterIds, staffIds, childCenterIds, childGroupIds, childIds
      }).then(response => {
          this.reset();
          console.log(response)
          this.messageId = response.messageId
          // this.showUndoButton = true
          this.showUndoBox = true
          this.undoTip = this.$t('loc.MessageSent')
          setTimeout(() => {
            this.showUndoBox = false
          }, 5000)
        })
        .catch(error => {
          console.log(error)
          this.$message.error(error.response.data.description)
        })
        .finally(() => this.sending = false);
    },
    handleClickCloseSendResult() {
      this.sendResult.show = false;
    },
    reset() {
      // 重置接收人
      this.$refs.recipientSelectTree.reset();
      // 重置主题
      this.$refs.subjectFormItem.resetField();
      // 重置消息内容
      this.$refs.contentFormItem.resetField();
      // 重置附件
      // this.$refs.attachmentFormItem.reset();
    },
    handleCheckRecipient() {
      this.$refs.recipientSelect.validate();
    },
    undoSend () {
      if (!this.undoing) {
        this.undoing = true
        MessageApi.undoSendMessage(this.messageId).then(res => {
          this.showUndoButton = false
          this.undoTip = this.$t('loc.MessageUndo')
          this.form = this.history.form
          this.recipient = this.history.recipient
          this.receiveRole = this.history.receiveRole
          this.attachments = this.history.attachments
          this.$refs.recipientSelectTree.setChecks(this.history.checkes)
          this.history = {}
        }).catch(error => {
          this.$message.error(error.response.data.description)
        })
          .finally(() => {
          this.undoing = false
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
.el-row /deep/ & {
  height: 100%;
  padding: 16px 32px 0;
  gap: 15px;
  color: #303133;
  flex-wrap: nowrap;
  & > :first-child {
    overflow-y: auto;
  }

  & > :last-child {
    overflow-y: auto;
    padding: 0 20px;
  }
}

.school-message-subject__input /deep/ & {
  input.el-input__inner {
    padding-right: 55px;
    font-weight: bold;
    color: inherit;

    &::placeholder {
      font-weight: normal;
    }
  }
}

.el-form-item /deep/ & {
  margin-bottom: 16px;

  .el-form-item__error {
    padding-left: 0;
  }
}

.el-divider--horizontal {
  margin-top: 0;
  margin-bottom: 16px;
}
</style>